#!/usr/bin/env python3
import argparse
import logging
from operator import index
import os
import sys
import threading
import csv
import re

import urllib3

from pyzabbix import ZabbixAPI


urllib3.disable_warnings()

def get_zabbix_connection(zbx_url, zbx_user, zbx_password):
    """
    Sometimes pyzabbix and py-zabbix library can replace each other.
    This is a wrapper, we don't care about what pip-module we install.
    Return ZabbixAPI object
    """
    # pyzabbix library, with user\password in login method. It's GOOD library
    logging.debug("Try connect to Zabbix by pyzabbix...")
    try:
        zbx_pyzabbix = ZabbixAPI(zbx_url)
        zbx_pyzabbix.session.verify = False
        zbx_pyzabbix.login(zbx_user, zbx_password)
        return zbx_pyzabbix
    except Exception as e:
        logging.exception(e)

    # py-zabbix library, with user\password in ZabbixAPI
    logging.debug("Try connect to Zabbix by py-zabbix...")
    try:
        zbx_py_zabbix = ZabbixAPI(zbx_url, user=zbx_user, password=zbx_password)
        zbx_py_zabbix.session.verify = False
        return zbx_py_zabbix
    except Exception as e:
        logging.exception(e)
    # choose good API

    raise Exception("Some error in pyzabbix or py_zabbix module, see logs")

def environ_or_required(key):
    "Argparse environment vars helper"
    if os.environ.get(key):
        return {"default": os.environ.get(key)}
    else:
        return {"required": True}

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--zabbix-url",
        action="store",
        help="REQUIRED. May be in ZABBIX_URL env var",
        **environ_or_required("ZABBIX_URL")
    )
    parser.add_argument(
        "--zabbix-username",
        action="store",
        help="REQUIRED. May be in ZABBIX_USERNAME env var",
        **environ_or_required("ZABBIX_USERNAME")
    )
    parser.add_argument(
        "--zabbix-password",
        action="store",
        help="REQUIRED. May be in ZABBIX_PASSWORD env var",
        **environ_or_required("ZABBIX_PASSWORD")
    )

    parser.add_argument("--debug", action="store_true", help="Show debug output")


    args = parser.parse_args()
    return args

def init_logging(level):
    logger_format_string = "%(asctime)s %(levelname)-8s %(message)s"
    logging.basicConfig(level=level, format=logger_format_string, stream=sys.stdout)

def get_item_cache(zabbix, hostname):
    "Return dict 'hostname'=>itemid"
    result = zabbix.item.get(
        output=["itemid","key_","type","delay","name","status"],
        selectHosts=["name"],
        sortfield="name",
        webitems=True,
        search= {
            "type": "2",
        },
        filter={"host": hostname},
    )
    # item2itemid = {}  # key: "hostname,itemname", value: itemid
    # for i in result:
    #     if i["type"] == "2":
    #         item2itemid["{}".format(i["itemid"])] = i["key_"]
    return result

def get_history_cache(zabbix, itemid):
    "Return dict history object"
    result = zabbix.history.get(output = "extend", itemids = itemid)
    return result

def get_proxy_cache(zabbix):
    "Return dict proxyname=>proxyid or None on error"
    result = zabbix.proxy.get(output=["proxyid", "host"])
    proxy2proxyid = {}  # key: proxy name, value: proxyid
    for proxy in result:
        proxy2proxyid[proxy["proxyid"]] = proxy["host"]
    return proxy2proxyid

def update_item(zabbix, itemid, typeid, delay):
    zabbix.item.update(itemid=itemid,type=typeid,delay=delay)

if __name__ == "__main__":
    args = parse_args()
    level = logging.INFO
    if args.debug:
        level = logging.DEBUG
    init_logging(level=level)
    is_restore= False
    is_host = True
    try:
        zabbix_ = get_zabbix_connection(
            args.zabbix_url, args.zabbix_username, args.zabbix_password
        )
        hosts = zabbix_.host.get(output=["host","status","hostid","proxy_hostid"], search={"status": "0"})
        proxy2proxyid = get_proxy_cache(zabbix_)
        print(proxy2proxyid)
        with open("host_history.txt", "w") as fh:
            for host in hosts:
                logging.info(host["host"])

                hostGroupid = zabbix_.hostgroup.get(output=["name"], hostids=host["hostid"])
                if hostGroupid[0]["name"] != "GameFusdmv":
                    continue
                fh.write(str(host["host"])+"\n")
                proxyName = "default"
                if host["proxy_hostid"] in proxy2proxyid:
                    proxyName=proxy2proxyid[host["proxy_hostid"]]
                items = get_item_cache(zabbix_, host["host"])
                # if host["status"] != "0":
                #     continue
                os.makedirs("./history/" + proxyName + "/" + hostGroupid[0]["name"], exist_ok=True)
                fileName = "./history/" + proxyName + "/" + hostGroupid[0]["name"] + "/" + host["host"] +".conf"
                for item in items:
                    if item["status"] != "0":
                        continue
                    history_message = get_history_cache(zabbix_, item["itemid"])
                    for history in history_message:
                        # item["name"] = re.sub("/", "_", item["name"])
                        # fileName = "./history/" + proxyName + "/" + hostGroupid[0]["name"] + "/" + host["host"] + item["name"] + ".conf"
                        fileName = "./history/" + proxyName + "/" + hostGroupid[0]["name"] + "/" + host["host"] + ".conf"
                        with open(fileName, "a+") as f:
                            sender_message = host["host"] + " " + item["key_"] + " " + history["clock"] + " " + history["ns"] + " " + history["value"] + "\n"
                            f.write(str(sender_message))
        logging.info("Done")
    except Exception as e:
        logging.error(e)


